package com.hanserwei.community.config;

import com.hanserwei.community.uitils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String token = request.getHeader("authorization");
        log.info("Intercepted request with token: {}", token);
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        String jwt = token.substring(7);

        try {
            Claims claims = JWTUtils.parseToken(jwt);
            String refreshedToken = JWTUtils.refreshToken(claims);

            // 将刷新后的 token 写回响应头，前端可用该值替换本地 token
            response.setHeader("Authorization", "Bearer " + refreshedToken);
            response.setHeader("Access-Control-Expose-Headers", "Authorization");

            Number userId = claims.get("userId", Number.class);
            if (userId != null) {
                request.setAttribute("userId", userId.longValue());
            }
            request.setAttribute("userName", claims.get("userName", String.class));
            request.setAttribute("userType", claims.get("userType", Integer.class));
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }
}
